import React, {Component} from 'react';
import {Relax, msg} from 'iflux2';
import {Map, OrderedSet, List} from 'immutable';
import {Link} from 'react-router';

import {Table, Row, Col, Button, Spin, Icon, message} from 'antd';

import {listQL} from '../ql';
import {orderColumns, renderOrderFilter} from '../constant/columns';
import {orderStatus} from '../constant/order-status';

import OrderIterm from './order-item';
import Pages from './pages';
import EmptyBody from './empty-body';

import noop from 'util/noop';
import classNames from 'classnames';

@Relax
export default class OrderList extends Component {
    static defaultProps = {
        //数据
        list: listQL,
        filterKey: 'ALL',
        type: 'sales',
        expressCompany: List(),
        //方法处理
        startExportOrder: noop,
        queryOrderList: noop,
        setOrderStatus: noop,
        resetPagination: noop,
        deliveryOrder: noop,
        copyTrade: noop,
        getExpand: noop
    };


    constructor(props) {
        super(props);

        this.state = {
            selectedRowKeys: [],
            loading: true,
            filterDropdownVisible: false
        }
    }


    componentDidMount() {
        msg.on('setLoading', (loading)=>{
            this.setLoading(loading);
        })
    }


    render() {
        let {list, type, getExpand} = this.props;
        let {selectedRowKeys, loading} = this.state;

        const rowSelection = {
            selectedRowKeys: selectedRowKeys,
            onSelectAll: (selected, selectedRows, changeRows)=>this.selectAll(selected, selectedRows, changeRows)
        };

        const orderHear = (<Table pagination={false}
                                  rowSelection={rowSelection}
                                  columns={this.renderColumns()}
                                  dataSource={list.toJS()}/>);

        let selectAll = list.filterNot(order=>OrderedSet(selectedRowKeys).has(order.get('tid'))).isEmpty();
        let indeterminate = !selectAll && !OrderedSet(selectedRowKeys).isEmpty();


        return (
            <Spin spinning={loading}>
                {this.renderToolBar()}
                <div className="order-list-table">
                    <div className="order-list-table-hd">{orderHear}</div>
                    <div className="order-list-table-bd">
                        {
                            list.isEmpty()
                                ?
                                <EmptyBody/>
                                :
                                list.map((order, index)=><OrderIterm key={index}
                                                                     type={type}
                                                                     order={order}
                                                                     selectRow={(tid)=>this.selectRow(tid)}
                                                                     selectedRowKeys={OrderedSet(selectedRowKeys)}/>)
                        }
                    </div>
                </div>
                {
                    list.isEmpty() ? null : <Pages 
                                                indeterminate={indeterminate}
                                                selectAll={selectAll}
                                                selectAll4Page={(selectAll)=>this.selectAll4Page(selectAll)}
                                            />
                }
            </Spin>
        )
    }


    /**
     * 渲染toolBar
     * @returns {XML}
     */
    renderToolBar() {
        return (
            <Row className="table-toolbar">
                <Col span={12}>
                    <Link to="/order/start"><Button type="primary">代客下单</Button></Link>
                    <Button type="ghost" onClick={()=>this.startExportOrder()}>导出</Button>
                    <a href="//oauth.qianmi.com" target="_blank"><Button type="ghost">打印</Button></a>
                </Col>
            </Row>
        );
    }


    /**
     * 扩展最后一列
     * @returns {*|{options, browsertest, dist, rhino, rhinolessc}|Buffer|Array.<T>|string}
     */
    renderColumns() {
        const {filterKey, type} = this.props;
        let { filterDropdownVisible} = this.state;
        const _this = this;

       return orderColumns(type).concat([{
           title: orderStatus[filterKey],
           width: 270,
           key: 'state',
           className:"ant-table-th-right pr8 va-t",
           filterDropdown: (
               <div className="w100 bd" style={{backgroundColor: '#fff'}}>{_this.renderButton()}</div>
           ),
           filterIcon: <Icon type="down-circle-o"/>,
           filterDropdownVisible: filterDropdownVisible,
           onFilterDropdownVisibleChange: visible=>_this.onFilterDropdownVisibleChange(visible)
       }]);
    }


    renderButton() {
        const {filterKey, type} = this.props;
        const orderStatusList = renderOrderFilter(type);

        return orderStatusList.map((status, index)=>{
            let {name, key} = status;
            let buttonCls = classNames('ml10 w80', {
                pusht: index == 0,
                pushb: orderStatusList.length == index + 1,
                mt5: index != 0
            });

            return <Button key={key}
                           className={buttonCls}
                           onClick={()=>this.changeOrderStatus(key)}
                           type={filterKey == key ? 'primary' : 'ghost'}>{name}</Button>
        })
    }

    onFilterDropdownVisibleChange(visible) {
        this.setState({
            filterDropdownVisible: visible
        })
    }

    /**
     * 切换不同订单状态列表
     * @param filterKey
     */
    changeOrderStatus(filterKey) {
        const {setOrderStatus, resetPagination} = this.props;
        setOrderStatus(filterKey);
        resetPagination();
        this.setState({
            filterDropdownVisible: false
        });
        this.queryOrderList();
    }


    /**
     * 全选操作
     * @param selected
     * @param selectedRows
     * @param changeRows
     */
    selectAll(selected, selectedRows, changeRows) {
        let selectedRowKeys = [];
        selected && selectedRows.forEach(row=>selectedRowKeys.push(row.tid));
        this.setState({selectedRowKeys});
    }


    /**
     *选择列操作
     * @param tid
     */
    selectRow(tid) {
        let selectedRowKeys = OrderedSet(this.state.selectedRowKeys);
        this.setState({
            selectedRowKeys: selectedRowKeys[selectedRowKeys.has(tid) ? 'delete' : 'add'](tid).toJS()
        })
    }


    /**
     * 给分页页面使用的全选操作
     * @param selectAll
     */
    selectAll4Page(selectAll) {
        let selectedRowKeys = [];
        selectAll && this.props.list.forEach(order=>selectedRowKeys.push(order.get('tid')));
        this.setState({selectedRowKeys});
    }



    filter(value, record) {
        this.setState({
            filterName: value
        });
        return true;
    }


    /**
     * 导出订单
     */
    startExportOrder() {
        const {selectedRowKeys} = this.state;
        if (selectedRowKeys.length) {
            this.props.startExportOrder(selectedRowKeys)
        }else {
            message.warn('请选择订单');
        }
    }


    queryOrderList() {
        this.setLoading(true);
        //查询订单列表
        this.props.queryOrderList().then(()=>{
            this.setLoading(false);
        }).catch(()=>{
            this.setLoading(false);
        });
    }

    /**
     * 设置loading状态
     * @param loading
     */
    setLoading = (loading)=>{
        this.setState({loading})
    }
}